#include "daouser.h"

#include <QtSql>
#include <QDebug>

#include "sql.h"
#include "utildb.h"

int UserDao::insert(const User user)
{
    DbUtil& dbUtil = DbUtil::getInstance();
    QSqlQuery query(dbUtil.getDatabase());
    query.prepare(SQL_INSERT_USER);

    query.addBindValue(user.currentVocabularyId());
    query.addBindValue(user.groupSize());
    query.addBindValue(user.currentGroup());

    if (!query.exec()) {

        qDebug() << query.lastError();
        qDebug() << query.lastError();
        return -1;
    }
    int id = query.lastInsertId().toInt();
    dbUtil.close();

    return id;
}

bool UserDao::update(const User& user)
{
    DbUtil& dbUtil = DbUtil::getInstance();
    QSqlQuery query(dbUtil.getDatabase());
    query.prepare(SQL_UPDATE_USER);

    query.addBindValue(user.currentVocabularyId());
    query.addBindValue(user.groupSize());
    query.addBindValue(user.id());

    bool flag = query.exec();
    dbUtil.close();
    return flag;
}
bool UserDao::updateCurrentGroup(int group, const User& user)
{
    DbUtil& dbUtil = DbUtil::getInstance();
    QSqlQuery query(dbUtil.getDatabase());
    query.prepare(SQL_UPDATE_USER_CURRENT_GROUP);

    query.addBindValue(group);
    query.addBindValue(user.id());

    bool flag = query.exec();
    dbUtil.close();
    return flag;
}

User UserDao::query()
{
    User user;
    DbUtil& dbUtil = DbUtil::getInstance();
    QSqlQuery query(dbUtil.getDatabase());

    query.exec(SQL_SELECT_USER_ALL);
    if (query.next()) {
        user.parseRecord(query.record());
    }

    dbUtil.close();

    return user;
}

UserDao::UserDao()
{

}
